﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.EBS.Domain.Services
{
    public class RegisterService
    {
        public ServiceResult Register(Guid appId, string appToken, string @namespace, string @event, string callback)
        {
            NamespaceEntry nsEntry = Storage.GetOrCreate(@namespace);
            EventEntry eventEntry = nsEntry.GetOrCreate(@event, appId, callback);
            Logger.InfoToTag(Library.LogTAG, string.Format("Register,app:{0},token:{1},ns:{2},e:{3},callback:{4}", appId, appToken, @namespace, @event, callback));
            return new ServiceResult();
        }

        public ServiceResult Unregister(Guid appId, string appToken, string @namespace, string @event)
        {
            Logger.InfoToTag(Library.LogTAG, string.Format("Unregister,app:{0},token:{1},ns:{2},e:{3}", appId, appToken, @namespace, @event));
            NamespaceEntry nsEntry = Storage.Get(@namespace);
            if(nsEntry!=null)
            {
                nsEntry.Remove(@event, appId);
                if(nsEntry.Events.Count == 0)
                {
                    Logger.DebugToTag(Library.LogTAG, string.Format("Unregister-Remove,app:{0},token:{1},ns:{2},e:{3}", appId, appToken, @namespace, @event));
                    Storage.Remove(nsEntry);
                }
            }
            return new ServiceResult();
        }
    }
}
